package com.zhida.jiyangcenter.membership

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.manager.app
import chooongg.base.utils.tipFail
import chooongg.base.utils.tipWarn
import chooongg.base.utils.toast
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIPay
import com.zhida.jiyangcenter.api.AlipayEntity
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.WechatEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.mian.MainActivity
import com.zhida.jiyangcenter.order.PayTypeEntity
import com.zhida.jiyangcenter.utils.AliPay
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import com.zhida.jiyangcenter.wxapi.WXPayEntryActivity
import kotlinx.android.synthetic.main.activity_pay_member.*
import kotlinx.android.synthetic.main.activity_pay_recharge.*
import kotlinx.android.synthetic.main.activity_pay_recharge.rv_pay_order
import kotlinx.android.synthetic.main.activity_pay_recharge.title_bar
import kotlinx.android.synthetic.main.activity_pay_recharge.tv_bottom_money
import kotlinx.android.synthetic.main.activity_pay_recharge.tv_money
import kotlinx.android.synthetic.main.activity_pay_recharge.tv_pay

@TitleBar(false)
@ContentLayout(R.layout.activity_pay_recharge)
class PayRechargeActivity:BaseActivity() {
    val adapter = Adapter()
    @SuppressLint("SetTextI18n")
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.title("购买详情").navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        tv_money.text="￥${intent.getStringExtra("balance")?:"0.00"}"
        tv_yue.text="￥${intent.getStringExtra("balance")?:"0.00"}"
        tv_account.text="当前账户：${intent.getStringExtra("account")}"
        tv_bottom_money.text="支付：${intent.getIntExtra("pay_money",0)}元"
        rv_pay_order.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_pay_order.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerSmall)
                .colorResId(R.color.colorBack).build()
        )
        rv_pay_order.adapter = adapter
        adapter.setNewData(ArrayList<PayTypeEntity>().apply {
            add(PayTypeEntity(R.drawable.iv_pay_wechat, "微信支付", ""))
            add(PayTypeEntity(R.drawable.iv_pay_alipay, "支付宝支付", ""))
        })
        adapter.setOnItemClickListener { _, _, position ->
            adapter.position = position
            adapter.notifyDataSetChanged()
        }
        val code=intent.getStringExtra("order_code")
        tv_pay.setOnClickListener {
            when (adapter.position) {
                -1 -> {
                    toast("请选择支付方式")
                }
                0-> {
                    lifecycleScope.request({
                        APIPay.service().wxpay(
                            code,
                            "6"
                        )
                    }, object : BaseAPI<WechatEntity>() {
                        override fun onSuccess(response: WechatEntity?, state: Int, msg: String) {
                            WXPayEntryActivity.setWxPay {
                                for (i in app.activityStack.size - 1 downTo 0) {
                                    if (app.activityStack[i] !is MainActivity) {
                                        app.activityStack[i].finish()
                                    }
                                }
                                finish()
                            }
                            wechatRecharge(
                                response?.appid,
                                response?.noncestr,
                                response?.`package`,
                                response?.partnerid,
                                response?.prepayid,
                                response?.sign,
                                response?.timestamp
                            )
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                }
                1 -> {
                    lifecycleScope.request({
                        APIPay.service().alipay(
                            code,
                            "6"
                        )
                    }, object : BaseAPI<AlipayEntity>() {
                        override fun onSuccess(t: AlipayEntity?, state: Int, msg: String) {
                            AliPay(activity).pay(
                                t?.order_string ?: "",
                                "6",
                                code,
                            0.00,0)
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                    })
                }
            }
        }
    }
    private fun wechatRecharge(
        appid: String?,
        noncestr: String?,
        `package`: String?,
        partnerid: String?,
        prepayid: String?,
        sign: String?,
        timestamp: String?
    ) {
        if (appid == null || noncestr == null || `package` == null || partnerid == null
            || prepayid == null || sign == null || timestamp == null
        ) {
            tipWarn("支付环境异常")
            return
        }
        val msgApi = WXAPIFactory.createWXAPI(context, null)
        msgApi.registerApp(appid)
        val request = PayReq().apply {
            this.appId = appid
            this.nonceStr = noncestr
            this.packageValue = `package`
            this.partnerId = partnerid
            this.prepayId = prepayid
            this.sign = sign
            this.timeStamp = timestamp
        }
        msgApi.sendReq(request)
    }

    class Adapter : BaseQuickAdapter<PayTypeEntity, BaseViewHolder>(R.layout.item_pay_type) {
        var position = -1
        override fun convert(helper: BaseViewHolder, item: PayTypeEntity) {
            helper.getView<SmoothCheckBox>(R.id.check_box)
                .setChecked(position == helper.layoutPosition - headerLayoutCount, true)
            helper.setImageResource(R.id.iv_pay_type, item.drawableInt)
                .setText(R.id.tv_pay_type_name, item.name)
                .setText(R.id.tv_pay_type_money, item.money)
        }

    }
}